package com.gitee.zycra.future.job.web.controller;

import com.gitee.zycra.future.job.common.bo.CommonResult;
import com.gitee.zycra.future.job.common.vo.EnumOptionVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zycra
 */
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    private static final String ENUM_PREFIX = "com.gitee.zycra.future.job.common.enums.";

    private static final String ENUM_SUBFIX = "Enum";

    private static final String GET_MAP_METHOD = "getMap";

    /**
     * 根据类名获取枚举值
     *
     * @param enumNames 类名集合
     * @return 枚举值集合
     */
    @SuppressWarnings("unchecked")
    @GetMapping("/enumOptionList")
    public CommonResult<Map<String, List<EnumOptionVO>>> enumOptionList(@RequestParam("enumNames") List<String> enumNames) {
        if (CollectionUtils.isEmpty(enumNames)) {
            log.warn("类名集合为空");
            return CommonResult.failed();
        }
        Map<String, List<EnumOptionVO>> result = new HashMap<>();
        List<EnumOptionVO> list;
        for (String enumName : enumNames) {
            try {
                Class<?> clazz = Class.forName(ENUM_PREFIX + enumName + ENUM_SUBFIX);
                Object res = clazz.getMethod(GET_MAP_METHOD).invoke(null);
                if (res instanceof Map) {
                    list = new ArrayList<>();
                    Map<Integer, String> map = (Map<Integer, String>) res;
                    for (Map.Entry<Integer, String> entry : map.entrySet()) {
                        list.add(new EnumOptionVO().setValue(entry.getKey()).setLabel(entry.getValue()));
                    }
                    result.put(enumName, list);
                }
            } catch (ClassNotFoundException e) {
                log.error("未找到枚举类, enumName={}", enumName, e);
            } catch (Exception e) {
                log.error("执行方法异常, enumName={}", enumName, e);
            }
        }
        return CommonResult.success(result);
    }
}
